<template>
  <div class="attendance-container">
    <h1 class="page-title">签到管理</h1>
    
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 待签到课程 -->
      <el-tab-pane label="待签到课程" name="pending">
        <div class="attendance-header">
          <div class="header-info">
            <h3>今日待签到课程</h3>
            <p>{{ currentDate }}</p>
          </div>
          <el-button type="primary" @click="refreshAttendance">
            <el-icon><Refresh /></el-icon> 刷新
          </el-button>
        </div>
        
        <el-empty v-if="pendingCourses.length === 0" description="今日无待签到课程" />
        
        <div v-else class="course-list">
          <el-card v-for="course in pendingCourses" :key="course.id" class="course-card" shadow="hover">
            <div class="course-info">
              <div class="course-name">{{ course.name }}</div>
              <div class="course-details">
                <div class="detail-item">
                  <el-icon><User /></el-icon>
                  <span>{{ course.teacher }}</span>
                </div>
                <div class="detail-item">
                  <el-icon><Location /></el-icon>
                  <span>{{ course.location }}</span>
                </div>
                <div class="detail-item">
                  <el-icon><Timer /></el-icon>
                  <span>{{ course.time }}</span>
                </div>
                <div class="detail-item">
                  <el-icon><Clock /></el-icon>
                  <span>{{ course.status }}</span>
                </div>
              </div>
            </div>
            <div class="course-action">
              <el-tag v-if="course.status === '已结束'" type="info">已结束</el-tag>
              <el-tag v-else-if="course.status === '未开始'" type="warning">未开始</el-tag>
              <el-button 
                v-else 
                type="primary" 
                :disabled="course.signedIn" 
                @click="handleSignIn(course)"
              >
                {{ course.signedIn ? '已签到' : '签到' }}
              </el-button>
            </div>
          </el-card>
        </div>
      </el-tab-pane>
      
      <!-- 签到记录 -->
      <el-tab-pane label="签到记录" name="records">
        <div class="filter-container">
          <el-form :inline="true" :model="filterForm" class="filter-form">
            <el-form-item label="课程名称">
              <el-input v-model="filterForm.courseName" placeholder="请输入课程名称" clearable />
            </el-form-item>
            <el-form-item label="签到状态">
              <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
                <el-option label="已签到" value="已签到" />
                <el-option label="缺勤" value="缺勤" />
                <el-option label="请假" value="请假" />
                <el-option label="迟到" value="迟到" />
              </el-select>
            </el-form-item>
            <el-form-item label="日期范围">
              <el-date-picker
                v-model="filterForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleFilter">查询</el-button>
              <el-button @click="resetFilter">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <el-table :data="filteredRecords" style="width: 100%" border v-loading="loading">
          <el-table-column prop="date" label="日期" width="120" sortable />
          <el-table-column prop="time" label="时间" width="100" />
          <el-table-column prop="courseName" label="课程名称" width="180" />
          <el-table-column prop="teacher" label="任课教师" width="120" />
          <el-table-column prop="location" label="上课地点" width="120" />
          <el-table-column prop="status" label="签到状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="signInTime" label="签到时间" width="180" />
          <el-table-column prop="remark" label="备注" />
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalRecords"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        
        <div class="attendance-statistics">
          <h3>签到统计</h3>
          <div class="statistics-overview">
            <div class="statistics-chart">
              <div class="chart-container">
                <div class="progress-ring">
                  <div class="progress-circle" :style="`--percentage: ${statistics.attendanceRate}; --color: #409EFF;`">
                    <div class="progress-value">{{ statistics.attendanceRate }}<span>%</span></div>
                    <div class="progress-label">出勤率</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="statistics-summary">
              <div class="summary-card">
                <div class="summary-header">
                  <span>本学期课程总数</span>
                </div>
                <div class="summary-value">
                  <span class="value-number">{{ statistics.total }}</span>
                  <span class="value-unit">课时</span>
                </div>
              </div>
            </div>
          </div>
          
          <div class="statistics-details">
            <div class="detail-card status-attended">
              <div class="detail-icon">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="detail-content">
                <div class="detail-value">{{ statistics.attended }}</div>
                <div class="detail-label">已签到</div>
              </div>
              <div class="detail-percentage">{{ Math.round(statistics.attended / statistics.total * 100 || 0) }}%</div>
            </div>
            
            <div class="detail-card status-late">
              <div class="detail-icon">
                <el-icon><Timer /></el-icon>
              </div>
              <div class="detail-content">
                <div class="detail-value">{{ statistics.late }}</div>
                <div class="detail-label">迟到</div>
              </div>
              <div class="detail-percentage">{{ Math.round(statistics.late / statistics.total * 100 || 0) }}%</div>
            </div>
            
            <div class="detail-card status-leave">
              <div class="detail-icon">
                <el-icon><Document /></el-icon>
              </div>
              <div class="detail-content">
                <div class="detail-value">{{ statistics.leave }}</div>
                <div class="detail-label">请假</div>
              </div>
              <div class="detail-percentage">{{ Math.round(statistics.leave / statistics.total * 100 || 0) }}%</div>
            </div>
            
            <div class="detail-card status-absent">
              <div class="detail-icon">
                <el-icon><WarningFilled /></el-icon>
              </div>
              <div class="detail-content">
                <div class="detail-value">{{ statistics.absent }}</div>
                <div class="detail-label">缺勤</div>
              </div>
              <div class="detail-percentage">{{ Math.round(statistics.absent / statistics.total * 100 || 0) }}%</div>
            </div>
          </div>

        </div>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 签到确认对话框 -->
    <el-dialog v-model="signInDialogVisible" title="课程签到" width="30%">
      <div v-if="currentCourse">
        <div class="sign-in-info">
          <h3>{{ currentCourse.name }}</h3>
          <p><el-icon><User /></el-icon> {{ currentCourse.teacher }}</p>
          <p><el-icon><Location /></el-icon> {{ currentCourse.location }}</p>
          <p><el-icon><Timer /></el-icon> {{ currentCourse.time }}</p>
        </div>
        
        <div class="sign-in-qrcode">
          <div class="qrcode-container">
            <img src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=attendance_code_123456" alt="签到二维码" />
          </div>
          <p class="qrcode-tip">请使用手机扫描二维码进行签到</p>
        </div>
        
        <div class="sign-in-code">
          <p>或输入签到码：</p>
          <el-input v-model="signInCode" placeholder="请输入签到码" maxlength="6">
            <template #append>
              <el-button @click="handleCodeSignIn">确认</el-button>
            </template>
          </el-input>
        </div>
        
        <div class="sign-in-location">
          <p>位置信息：</p>
          <el-tag type="success">已获取位置信息，符合签到范围</el-tag>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="signInDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSignIn">扫码签到</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 签到成功对话框 -->
    <el-dialog v-model="successDialogVisible" title="签到成功" width="30%" center>
      <div class="success-dialog">
        <el-icon class="success-icon"><CircleCheck /></el-icon>
        <h3>签到成功</h3>
        <p>您已成功签到{{ currentCourse ? currentCourse.name : '' }}课程</p>
        <p>签到时间：{{ new Date().toLocaleString() }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="successDialogVisible = false">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, User, Location, Timer, Clock, CircleCheck, Document, WarningFilled } from '@element-plus/icons-vue'
import { studentApi } from '@/api'

// 当前激活的标签页
const activeTab = ref('pending')

// 当前日期
const now = new Date()
const currentDate = ref(now.toLocaleDateString('zh-CN', { 
  year: 'numeric', 
  month: 'long', 
  day: 'numeric', 
  weekday: 'long' 
}))

// 加载状态
const loading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const totalRecords = ref(0)

// 筛选表单
const filterForm = ref({
  courseName: '',
  status: '',
  dateRange: []
})

// 待签到课程列表
const pendingCourses = ref([])

// 签到记录列表
const attendanceRecords = ref([])

// 签到统计
const statistics = ref({
  total: 0,
  attended: 0,
  late: 0,
  leave: 0,
  absent: 0,
  attendanceRate: 0
})

// 当前操作的课程
const currentCourse = ref(null)

// 签到码
const signInCode = ref('')

// 对话框可见性
const signInDialogVisible = ref(false)
const successDialogVisible = ref(false)

// 筛选后的记录
const filteredRecords = computed(() => {
  let filtered = [...attendanceRecords.value]
  
  if (filterForm.value.courseName) {
    filtered = filtered.filter(record => 
      record.courseName.toLowerCase().includes(filterForm.value.courseName.toLowerCase())
    )
  }
  
  if (filterForm.value.status) {
    filtered = filtered.filter(record => record.status === filterForm.value.status)
  }
  
  if (filterForm.value.dateRange && filterForm.value.dateRange.length === 2) {
    const startDate = new Date(filterForm.value.dateRange[0])
    const endDate = new Date(filterForm.value.dateRange[1])
    
    filtered = filtered.filter(record => {
      const recordDate = new Date(record.date)
      return recordDate >= startDate && recordDate <= endDate
    })
  }
  
  return filtered
})

// 初始化数据
onMounted(() => {
  fetchPendingCourses()
  fetchAttendanceRecords()
  fetchAttendanceStatistics()
})

// 获取待签到课程
const fetchPendingCourses = async () => {
  try {
    const res = await studentApi.getAttendance({ type: 'pending' })
    if (res.code === 200 && res.data) {
      pendingCourses.value = res.data
    }
  } catch (error) {
    console.error('获取待签到课程失败:', error)
    ElMessage.error('获取待签到课程失败')
  }
}

// 获取签到记录
const fetchAttendanceRecords = async () => {
  loading.value = true
  try {
    const res = await studentApi.getAttendance({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      courseName: filterForm.value.courseName,
      status: filterForm.value.status,
      startDate: filterForm.value.dateRange && filterForm.value.dateRange[0],
      endDate: filterForm.value.dateRange && filterForm.value.dateRange[1]
    })
    
    if (res.code === 200 && res.data) {
      attendanceRecords.value = res.data.list || []
      totalRecords.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取签到记录失败:', error)
    ElMessage.error('获取签到记录失败')
  } finally {
    loading.value = false
  }
}

// 获取考勤统计
const fetchAttendanceStatistics = async () => {
  try {
    const res = await studentApi.get('/student/attendance/statistics')
    if (res.code === 200 && res.data) {
      statistics.value = res.data
    }
  } catch (error) {
    console.error('获取考勤统计失败:', error)
  }
}

// 刷新签到列表
const refreshAttendance = () => {
  fetchPendingCourses()
}

// 处理签到
const handleSignIn = (course) => {
  currentCourse.value = course
  signInDialogVisible.value = true
}

// 确认签到
const confirmSignIn = async () => {
  if (!currentCourse.value) return
  
  try {
    const res = await studentApi.signIn({
      courseId: currentCourse.value.id,
      code: signInCode.value,
      location: {
        latitude: 30.123456,
        longitude: 120.123456
      }
    })
    
    if (res.code === 200) {
      signInDialogVisible.value = false
      successDialogVisible.value = true
      // 更新课程状态
      const index = pendingCourses.value.findIndex(item => item.id === currentCourse.value.id)
      if (index !== -1) {
        pendingCourses.value[index].signedIn = true
      }
      // 刷新统计数据
      fetchAttendanceStatistics()
    }
  } catch (error) {
    console.error('签到失败:', error)
    ElMessage.error('签到失败')
  }
}

// 通过签到码签到
const handleCodeSignIn = () => {
  if (!signInCode.value) {
    ElMessage.warning('请输入签到码')
    return
  }
  
  confirmSignIn()
}

// 获取状态对应的类型
const getStatusType = (status) => {
  switch (status) {
    case '已签到':
      return 'success'
    case '迟到':
      return 'warning'
    case '请假':
      return 'info'
    case '缺勤':
      return 'danger'
    default:
      return 'info'
  }
}

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1
  fetchAttendanceRecords()
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.value = {
    courseName: '',
    status: '',
    dateRange: []
  }
  currentPage.value = 1
  fetchAttendanceRecords()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAttendanceRecords()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchAttendanceRecords()
}
</script>

<style lang="scss" scoped>
.attendance-container {
  padding: 20px;
  
  .page-title {
    margin-bottom: 20px;
    font-size: 24px;
    font-weight: bold;
    color: #303133;
  }
  
  .attendance-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .header-info {
      h3 {
        margin: 0 0 5px;
        font-size: 18px;
        color: #303133;
      }
      
      p {
        margin: 0;
        font-size: 14px;
        color: #909399;
      }
    }
  }
  
  .course-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;
    
    .course-card {
      display: flex;
      flex-direction: column;
      
      .course-info {
        flex: 1;
        
        .course-name {
          font-size: 16px;
          font-weight: bold;
          margin-bottom: 10px;
          color: #303133;
        }
        
        .course-details {
          margin-bottom: 15px;
          
          .detail-item {
            display: flex;
            align-items: center;
            margin-bottom: 5px;
            color: #606266;
            
            .el-icon {
              margin-right: 5px;
            }
          }
        }
      }
      
      .course-action {
        display: flex;
        justify-content: flex-end;
        margin-top: 10px;
      }
    }
  }
  
  .filter-container {
    margin-bottom: 20px;
    background-color: #f5f7fa;
    padding: 15px;
    border-radius: 4px;
    
    .filter-form {
      display: flex;
      flex-wrap: wrap;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .attendance-statistics {
    margin-top: 30px;
    
    h3 {
      margin-bottom: 15px;
      font-size: 16px;
      font-weight: bold;
    }
    
    .statistics-overview {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;
      margin-bottom: 20px;
      
      .statistics-chart {
        flex: 1;
        min-width: 300px;
        
        .chart-container {
          position: relative;
          width: 100%;
          height: 200px; /* Adjust height as needed */
        }
        
        .progress-ring {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        
        .progress-circle {
          position: relative;
          width: 150px;
          height: 150px;
          border-radius: 50%;
          background: conic-gradient(
            var(--color) calc(var(--percentage) * 1%),
            #e9e9ef calc(var(--percentage) * 1%)
          );
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          
          &::before {
            content: '';
            position: absolute;
            inset: 10px;
            border-radius: 50%;
            background: white;
          }
        }
        
        .progress-value {
          position: relative;
          font-size: 28px;
          font-weight: bold;
          color: var(--color);
          z-index: 1;
          
          span {
            font-size: 14px;
            margin-left: 2px;
          }
        }
        
        .progress-label {
          position: relative;
          font-size: 14px;
          color: #606266;
          margin-top: 5px;
          z-index: 1;
        }
      }
      
      .statistics-summary {
        flex: 1;
        min-width: 200px;
        
        .summary-card {
          background-color: #f5f7fa;
          border-radius: 8px;
          padding: 15px;
          text-align: center;
          
          .summary-header {
            font-size: 14px;
            color: #606266;
            margin-bottom: 10px;
          }
          
          .summary-value {
            .value-number {
              font-size: 24px;
              font-weight: bold;
              color: #303133;
            }
            .value-unit {
              font-size: 14px;
              color: #909399;
            }
          }
        }
      }
    }
    
    .statistics-details {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
      gap: 15px;
      margin-bottom: 20px;
      
      .detail-card {
        display: flex;
        align-items: center;
        padding: 10px 15px;
        background-color: #f5f7fa;
        border-radius: 8px;
        border: 1px solid #ebeef5;
        
        .detail-icon {
          font-size: 24px;
          color: #409EFF;
          margin-right: 10px;
        }
        
        .detail-content {
          flex: 1;
          
          .detail-value {
            font-size: 18px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 5px;
          }
          
          .detail-label {
            font-size: 12px;
            color: #909399;
          }
        }
        
        .detail-percentage {
          font-size: 14px;
          color: #409EFF;
          font-weight: bold;
        }
        
        &.status-attended .detail-icon {
          color: #67C23A;
        }
        &.status-late .detail-icon {
          color: #E6A23C;
        }
        &.status-leave .detail-icon {
          color: #909399;
        }
        &.status-absent .detail-icon {
          color: #F56C6C;
        }
      }
    }
    
    .statistics-trend {
      h4 {
        margin-bottom: 15px;
        font-size: 16px;
        font-weight: bold;
      }
      
      .trend-chart {
        display: flex;
        align-items: flex-end;
        height: 100px; /* Adjust height as needed */
        background-color: #f5f7fa;
        border-radius: 8px;
        border: 1px solid #ebeef5;
        padding: 10px;
        box-sizing: border-box;
        
        .trend-bar {
          flex: 1;
          height: calc(var(--height) * 0.8%);
          background-color: var(--color);
          margin: 0 2px;
          border-radius: 3px 3px 0 0;
          position: relative;
          transition: height 0.3s ease;
          
          &:hover .trend-tooltip {
            opacity: 1;
          }
          
          &:first-child {
            margin-left: 0;
          }
          
          &:last-child {
            margin-right: 0;
          }
          
          .trend-tooltip {
            position: absolute;
            top: -30px;
            left: 50%;
            transform: translateX(-50%);
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 12px;
            white-space: nowrap;
            z-index: 10;
            opacity: 0;
            transition: opacity 0.2s ease;
          }
        }
      }
      
      .trend-labels {
        display: flex;
        justify-content: space-around;
        margin-top: 10px;
        font-size: 12px;
        color: #909399;
      }
    }
  }
  
  .sign-in-info {
    margin-bottom: 20px;
    
    h3 {
      margin: 0 0 10px;
      font-size: 18px;
      color: #303133;
    }
    
    p {
      display: flex;
      align-items: center;
      margin: 5px 0;
      color: #606266;
      
      .el-icon {
        margin-right: 5px;
      }
    }
  }
  
  .sign-in-qrcode {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;
    
    .qrcode-container {
      padding: 10px;
      border: 1px solid #ebeef5;
      border-radius: 4px;
      margin-bottom: 10px;
    }
    
    .qrcode-tip {
      color: #909399;
      font-size: 14px;
    }
  }
  
  .sign-in-code {
    margin-bottom: 20px;
    
    p {
      margin-bottom: 10px;
      color: #606266;
    }
  }
  
  .sign-in-location {
    p {
      margin-bottom: 10px;
      color: #606266;
    }
  }
  
  .success-dialog {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
    
    .success-icon {
      font-size: 60px;
      color: #67C23A;
      margin-bottom: 15px;
    }
    
    h3 {
      margin: 0 0 10px;
      font-size: 18px;
      color: #303133;
    }
    
    p {
      margin: 5px 0;
      color: #606266;
    }
  }
}

// 响应式样式
@media screen and (max-width: 768px) {
  .attendance-container {
    .course-list {
      grid-template-columns: 1fr;
    }
    
    .statistics-overview {
      flex-direction: column;
    }
    
    .statistics-chart {
      width: 100%;
    }
    
    .statistics-summary {
      width: 100%;
    }
    
    .statistics-details {
      grid-template-columns: 1fr;
    }
    
    .trend-chart {
      height: 80px; /* Adjust height for smaller screens */
    }
  }
}
</style> 